package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShopCartMapper;
import com.sky.properties.BaiDuMapProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderDetailVO;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.sky.utils.WeChatPayUtil;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private ShopCartMapper shopCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private BaiDuMapProperties baiDuMapProperties;

    private GeocodingDTO getAddressGeocoding(String address) {
        Map params = new LinkedHashMap<String, String>();
        params.put("address", address);
        params.put("output", "json");
        params.put("ak", baiDuMapProperties.getBaiDuAk());
        params.put("callback", "showLocation");
        String res = HttpClientUtil.doGet(baiDuMapProperties.getBaiDuUrl(), params);
        String str = res.substring(res.indexOf("(") + 1, res.lastIndexOf(")"));
        JSONObject jsonObject = JSON.parseObject(str);
        ResultGeocodingDTO resultGeocodingDTO = jsonObject.getObject("result", ResultGeocodingDTO.class);
        log.info("地理信息：{}", resultGeocodingDTO.getLocation());
        GeocodingDTO geocodingDTO = resultGeocodingDTO.getLocation();
        geocodingDTO.setLat(geocodingDTO.getLat().substring(0, geocodingDTO.getLat().length() - 8));
        geocodingDTO.setLng(geocodingDTO.getLng().substring(0, geocodingDTO.getLng().length() - 8));


        return geocodingDTO ;
    }

    private Integer getDistance(GeocodingDTO businessAddressInfo, GeocodingDTO userAddressInfo) {
        Map<String, String> addressMap = new HashMap<>();
        addressMap.put("origin", businessAddressInfo.getLat() + "," + businessAddressInfo.getLng());
        addressMap.put("destination", userAddressInfo.getLat() + "," + userAddressInfo.getLng());
        addressMap.put("ak", baiDuMapProperties.getBaiDuAk());

        String res = HttpClientUtil.doGet(baiDuMapProperties.getBaiDuDistinceUrl(), addressMap);
        log.info("距离返回：{}", res);
        JSONObject jsonObject = JSON.parseObject(res);
        Integer statusCode = (Integer) jsonObject.get("status");
        log.info("statusCode: {}", statusCode);


        return statusCode;


    }
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 获取地址信息
        AddressBook addressBook = addressMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            // 地址不存在
            throw new BaseException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        GeocodingDTO businessAddressInfo = getAddressGeocoding(baiDuMapProperties.getBusiness());
        GeocodingDTO userAddressInfo = getAddressGeocoding(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());


        log.info("businessAddressInfo: {}", businessAddressInfo);
        log.info("businessAddressInfo: {}", userAddressInfo);

        Integer statusCode = getDistance(businessAddressInfo, userAddressInfo);
        if(statusCode == 2002) {
            throw new BaseException("超出距离");
        }
        if(statusCode == 2001) {
            throw new BaseException("无骑行路线");
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shopCartMapper.selectShoppingList(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
        order.setUserName(addressBook.getConsignee());

        //向订单表插入1条数据
        orderMapper.insert(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shopCartMapper.deleteShopCart(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        // // 当前登录用户id
        // Long userId = BaseContext.getCurrentId();
        // User user = userMapper.selectById(userId);
        //
        // //调用微信支付接口，生成预支付交易单
        // JSONObject jsonObject = weChatPayUtil.pay(
        //         ordersPaymentDTO.getOrderNumber(), //商户订单号
        //         new BigDecimal(0.01), //支付金额，单位 元
        //         "苍穹外卖订单", //商品描述
        //         user.getOpenid() //微信用户的openid
        // );
        //
        // if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        //     throw new OrderBusinessException("该订单已支付");
        // }
        //
        // OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        // vo.setPackageStr(jsonObject.getString("package"));
        //
        // return vo;

        /////////////////////////////////////////////////////////////////////
        // 模拟支付成功---修改订单状态
        // 业务处理，修改订单状态、来单提醒
        paySuccess(ordersPaymentDTO.getOrderNumber());
        // 返回一个空对象即可
        return new OrderPaymentVO();
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders=Orders.builder().id(ordersConfirmDTO.getId()).status(Orders.CONFIRMED).build();
        orderMapper.update(orders);
    }

    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) throws Exception {

        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus.equals(Orders.PAID)) {
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal("0.01"),
                    new BigDecimal("0.01"));
            log.info("申请退款：{}", refund);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }
    @Override
    public void repetition(Long id) {
        Long userId = BaseContext.getCurrentId();

        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());
        shopCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 查看订单
     * @return
     */
    @Override
    public OrderDetailVO selectOrder(Long orderId) {
        // 根据订单id查询订单
        Orders orders = orderMapper.selectOrder(orderId);
        // 根据订单id查询订单详细信息
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrder(orderId);
        // 封装OrderDetailVO对象并返回
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        // 拷贝数据
        BeanUtils.copyProperties(orders, orderDetailVO);
        orderDetailVO.setOrderDetailList(orderDetailList);
        return orderDetailVO;
    }

    /**
     * 取消订单
     * @param orderId
     */
    @Override
    public void updateCancel(Long orderId) throws Exception {
        // 查询订单信息
        Orders orders = orderMapper.selectOrder(orderId);
        String number = orders.getNumber();
        String amount = String.valueOf(orders.getAmount());
        BigDecimal bigDecimal = new BigDecimal(amount);
        // 判断是否存在订单
        if (orders == null){
            // 不存在返回订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 判断订单状态---- 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        if (orders.getStatus() < 2){
            // 修改订单状态
        }else {
            // 调用微信工具类WeChatPayUtil的refund方法申请退款
//            weChatPayUtil.refund(number, number, bigDecimal, bigDecimal);
            log.info("退款成功！！！！");
            // 修改支付状态--退款
            orders.setPayStatus(Orders.REFUND);
            orderMapper.update(orders);
        }
        // 修改订单状态--取消订单
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    /**
     * 分页查询历史订单
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageQuery(Integer page, Integer pageSize, Integer status) {
        //设置分页参数
        PageHelper.startPage(page, pageSize);
        //创建ordersDTO对象并将当前用户id赋值
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //分页查询
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList();

        //将订单详情封装进orderVO
        if (orders != null) {
            for (Orders orders1 : orders) {
                //获取id
                Long id = orders1.getId();

                //查询订单明细
                List<OrderDetail> orderDetailList = orderDetailMapper.getById(id);

                //赋值
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders1, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                //将orderVO添加到list中
                list.add(orderVO);
            }
        }
        assert orders != null;
        return new PageResult(orders.getTotal(), list);
    }

    /**
     * 订单搜索
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {

        //分页查询
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(dto);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        //返回PageResult
        return new PageResult(page.getTotal(),orderVOList);
    }

    /**
     * 获取订单菜品信息
     */
    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        //需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        //判断pageResult中是否为空，不为空则填充订单菜品信息
        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                //新建orderVO对象
                OrderVO orderVO = new OrderVO();

                //为orderVO对象赋值
                BeanUtils.copyProperties(orders, orderVO);

                //根据订单id获取菜品信息字符串
                String orderDishesStr = getOrderDishesStr(orders);

                //将订单信息封装到orderVO中并添加到orderVOList中去
                orderVO.setOrderDishes(orderDishesStr);
                orderVOList.add(orderVO);

            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(orders.getId());

        //将菜品订单信息拼接成字符串
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }
}
